package zjservice

// package main

import (
	"crypto/tls"
	"fmt"

	"doubimeizhi.com/utility"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	log "github.com/cihub/seelog"
)

var (
	servicehost   string = "service.app.qkier.com"
	serviceAppkey string = "40b3409b84ce4177b30056605e36e785"
	serviceSecret string = "9dd784c63eb14418832b024a053be883"
)

type ServiceItem struct {
	Code int                      `json:"code"`
	Msg  string                   `json:"msg"`
	Data []map[string]interface{} `json:"data"`
}

type SyncSeckillMsgResp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func GetServiceItem(serviceType int) *ServiceItem {
	nusb := utility.NewURLSignBuilder(serviceAppkey, serviceSecret, fmt.Sprintf("https://%s/v1/page/querycategory", servicehost))
	nusb.SetURLParam("type", fmt.Sprintf("%d", serviceType))
	reqURL := nusb.BuildURL()

	// reqURL := fmt.Sprintf("https://%s/v1/page/querycategory?appkey=40b3409b84ce4177b30056605e36e785&type=%d", activityhost, serviceType)
	b := httplib.Get(reqURL)
	b.SetHost(servicehost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp := &ServiceItem{}
	if err := b.ToJSON(resp); err != nil {
		fmt.Println(err.Error())
		return nil
	}
	return resp
}

func SyncSeckillMsg(serviceId int, sdId int64, acivityStatus, activityPrice int, regionCode []string) *SyncSeckillMsgResp {
	nusb := utility.NewURLSignBuilder(serviceAppkey, serviceSecret, fmt.Sprintf("https://%s/v1/service/updateactivitytype", servicehost))
	reqURL := nusb.BuildURL()

	// reqURL := fmt.Sprintf("https://%s/v1/service/updateactivitytype?appkey=40b3409b84ce4177b30056605e36e785", activityhost)
	b := httplib.Post(reqURL)
	b.SetHost(servicehost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})

	body := make(map[string]interface{})
	body["service_id"] = serviceId
	body["activity_type"] = 1
	body["sd_id"] = sdId
	body["activity_status"] = acivityStatus
	body["activity_price"] = activityPrice
	body["distinct_code"] = regionCode
	b.JSONBody(body)

	resp := &SyncSeckillMsgResp{}
	if err := b.ToJSON(resp); err != nil {
		fmt.Println(err.Error())
		log.Errorf("同步秒杀信息失败，err is : %s", err.Error())
		return nil
	}
	return resp
}

func init() {
	servicehost = beego.AppConfig.DefaultString("backsvr::service_host", "112.74.17.50")
	serviceAppkey = beego.AppConfig.DefaultString("backsvr::service_appkey", "40b3409b84ce4177b30056605e36e785")
	serviceSecret = beego.AppConfig.DefaultString("backsvr::service_secret", "9dd784c63eb14418832b024a053be883")
}

// func main() {
// 	// regionCode := []string{""}
// 	// resp := SyncSeckillMsg(17, 4, 2, 4300, regionCode)
// 	resp := GetServiceItem(1)
// 	fmt.Println(resp)
// }
